package lb.com.lingxi.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;

import java.util.List;
//跨域配置类
//作用：读取 cors 前缀的 YML 配置，生成 CORS 规则
@Data
@Configuration
@ConfigurationProperties(prefix = "cors")  // 绑定 yml 中 cors 前缀的配置
public class CorsConfig {
    private List<String> allowedOrigins;
    private String allowedMethods;
    private String allowedHeaders;
    private Boolean allowCredentials;
    private Long maxAge;

    // 生成 CORS 配置源，注入到 Spring 容器
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        // 绑定 yml 配置
        if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
            config.setAllowedOrigins(allowedOrigins);
        } else {
            // 默认允许所有源（仅开发环境）
            config.addAllowedOriginPattern("*");
        }
        
        if (allowedMethods != null) {
            config.setAllowedMethods(List.of(allowedMethods.split(",")));
        } else {
            config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        }
        
        if (allowedHeaders != null) {
            config.setAllowedHeaders(List.of(allowedHeaders.split(",")));
        } else {
            config.setAllowedHeaders(List.of("*"));
        }
        
        config.setAllowCredentials(allowCredentials != null ? allowCredentials : true);
        config.setMaxAge(maxAge != null ? maxAge : 3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);  // 对所有接口生效
        return source;
    }

}